package clients;

import java.awt.BorderLayout;

import java.awt.CardLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;

import com.alibaba.fastjson.JSON;

public class Test03Client extends JFrame implements ActionListener{
	JTextArea msgArea = new JTextArea();
    JTextArea infoArea = new JTextArea(1, 10);
    JTextField jf = new JTextField();
    JButton jb = new JButton("发送");
    
    Socket clientSocket;
    InputStream is;
    OutputStream os;
    PrintWriter pw;
    BufferedReader br;
    
    boolean isOpen = true;
    
	public static void main(String [] args){
		Test03Client mc = new Test03Client();
	}
	
	public Test03Client() {
		super("四方精创11楼聊天群");
		setLayout(new BorderLayout(5,5));
		JPanel p = new JPanel(new BorderLayout(5,5));
		JPanel jp = new JPanel(new BorderLayout(5,5));
        jb.addActionListener(this);
        msgArea.setEditable(false);
        infoArea.setEditable(false);
       
        //定义带滚动条的panel，并将JTextArea存入到panel中，使textarea具有滚动条显示功能。
        JScrollPane scrollMsg = new JScrollPane(msgArea);
        JScrollPane scrollUser = new JScrollPane(infoArea);
        //取消显示水平滚动条
        scrollMsg.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollUser.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        //显示垂直滚动条
        scrollMsg.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollUser.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        
        jp.add("Center", jf);
        jp.add("East", jb);
        p.add("Center", scrollMsg);
        p.add("South", jp);
        add("Center", p);
        add("East", scrollUser);
        
        super.setBounds(450, 200, 400, 300);
        super.setVisible(true);
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        try {
			connect("http://localhost:8888/server/socketServer", 10000);
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        
        super.addWindowListener(new WindowListener() {

			@Override
			public void windowOpened(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowClosing(WindowEvent e) {
				// TODO Auto-generated method stub
				if(pw != null) {
					pw.println("info&" + "lhn:退出群聊");
			        pw.flush();
		        	isOpen = false;
				}
			}

			@Override
			public void windowClosed(WindowEvent e) {
				// TODO Auto-generated method stub
			}

			@Override
			public void windowIconified(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowDeiconified(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowActivated(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowDeactivated(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
        	
        });
	}

	//建立连接
	private void connect(String path, int timeout) throws UnknownHostException, IOException {
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(path);
		//构建超时等配置信息
        RequestConfig config = RequestConfig.custom()
        		.setConnectTimeout(timeout) //连接超时时间
                .build();
        //设置请求配置时间
        post.setConfig(config);
        HttpResponse response = null;
        response = httpClient.execute(post);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			//发送到 ip 9999 端口
			clientSocket = new Socket("127.0.0.1", 9999);
			//输出流
	        os = clientSocket.getOutputStream();
	        pw = new PrintWriter(new OutputStreamWriter(os));
	        pw.println("info&" + "lhn:加入群聊");
	        pw.flush();
	        new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						//获取请求内容
					    String content;
					    Map<String, Object> resultMap;
					    while(isOpen) {
					    	is = clientSocket.getInputStream();
					    	br = new BufferedReader(new InputStreamReader(is));
					    	if((content = br.readLine()) != null) {
					    		resultMap =  JSON.parseObject(content, Map.class);
					    		if(resultMap != null) {
					    			List<String> info =  (List<String>) resultMap.get("info");
						    		List<String> msg = (List<String>) resultMap.get("msg");
					    			if(info != null) {
					    				infoArea.setText("");
					    				for(String resi : info) {
							    			infoArea.append(resi + "\r\n");
							    		}
					    			}
					    			if(msg != null) {
					    				msgArea.setText("");
					    				for(String resm : msg) {
					    					msgArea.append(resm + "\r\n");
							    		}
					    			}
					    		}
					    	}
					    }
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} finally {
		        		try {
		        			if(pw != null) {
				        		pw.close();
				        	}
		        			if(br != null) {
		        				br.close();
		        			}
		        			if(clientSocket != null) {
				        		clientSocket.close();
				        	}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}).start(); 
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == jb) {
			if(pw != null) {
				pw.println("msg&lhn:" + jf.getText());
		        pw.flush();
				jf.setText("");
			}
		}
	}
}
